import { directive } from "../ast/directive";

function generate(el){
  let children = getChildren(el);
  let code  = `_c('${el.tag}',${
      el.attrs.length>0 
      ? 
      `${formatProps(el.attrs)}`
      :
      'undefined'
    }
    
    
    ${
      children ? `,${children}`:''
    })`;
  return code;
  //${el.directives.length>0 ? directiveRender(el.directives) : ''}
}
function generateChild(node){
  if(node.type === 1){
    return generate(node);
  }else if(node.type === 3){
    let text = node.text;

    if(!defaultTagRE.test(text)){
      return `_v(${JSON.stringify(text)})`;
    }
    let match,
    index,
    lastIndex = defaultTagRE.lastIndex = 0,
    textArr = [];
    while(match= defaultTagRE.exec(text)){
      index = match.index;
      if(index >lastIndex){
        textArr.push(JSON.stringify(text.slice(lastIndex,index)))
      }
      textArr.push(`_s(${match[1].trim()})`);
      lastIndex = index + match[0].length;
    }
    if(lastIndex<text.length){
      textArr.push(JSPN.stringify(text.slice(lastIndex)))
    }
    return `_v(${textArr.join('+')})`
  }
}
function getChildren(el){
  const children = el.children;
  if(children){
    let a = children.map(c=>generateChild(c)).join(',');
    return a
  }
}
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;
function formatProps(attrs){
  let attrsString ='';
  
  for (let index = 0; index < attrs.length; index++) {
    let attr = attrs[index];
    if(attr.name === 'style'){
      let styleAttrs = {}
      attr.value.split(';').map( styleAttr=>{
        let [key,value] = styleAttr.split(':');
        styleAttrs[key] = value;
      })
      attr.value = styleAttrs;
      attrsString +=`${attr.name}:${JSON.stringify(attr.value)},`
    }
    if(attr.name === 'v-model'){
      attr.name = 'model'
      attrsString +=`directives:[{name:"model",rawName:"v-model",value:(${attr.value}),expression:${JSON.stringify(attr.value)}}],
      domProps:{"value":(${attr.value})},
      on:{"input":function($event){if($event.target.composing)return;${attr.value}=$event.target.value},
      `
    }if(attr.name === '@click'){
      attrsString +=`on:{"click":${JSON.stringify(attr.value)}},`
    }if(attr.name === '@input'){
      console.log(attr.value)
      attrsString +=`on:{"input":function($event){${attr.value}=$event.target.value}},value:_s(${attr.value}),`
    }
    
  }
  return `{${attrsString.slice(0,-1)}}`
}
function directiveRender(dir){
  if(dir.length>0){
    return `,{directives:[{name:"model",rawName:"v-model",value:(${dir[0].value}),expression:"sige"}]}`
  }
  
}
export {generate}